<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { dataPaymentMethodRanking } from '@/apis/apis.js'
import * as echarts from 'echarts/core'
import { TooltipComponent, GridComponent } from 'echarts/components'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer])

const paymentMethod = ref([])
const quantity = ref([])
const echartRef = ref(null)
const echartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      // Use axis to trigger tooltip
      type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
    }
  },
  grid: {
    left: '0%',
    right: '3%',
    top: '5%',
    bottom: '0%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: []
  },
  series: [
    {
      type: 'bar',
      label: {
        show: true
      },
      emphasis: {
        focus: 'series'
      },
      data: [],
      label: {
        show: true,
        position: 'right'
      }
    },
  ],
  color: ['orange']
})
let echart = null

const getData = async () => {
  const res = await dataPaymentMethodRanking()
  paymentMethod.value = res.data.paymentMethod
  quantity.value = res.data.quantity
}

const resize = () => {
  if (echart) {
    echart.resize()
  }
}

onMounted(async () => {
  await getData()
  echart = echarts.init(echartRef.value)
  echart.setOption(echartOption.value)
  window.addEventListener('resize', resize)
})

onUnmounted(() => {
  if (echart) {
    echart.dispose()
  }
  window.removeEventListener('resize', resize)
})

watch(paymentMethod, () => {
  echartOption.value.yAxis.data = paymentMethod.value
})

watch(quantity, () => {
  echartOption.value.series[0].data = quantity.value
})
</script>

<template>
  <div class="container">
    <div class="title" style="display: flex; align-items: center; height: 32px;">支付渠道</div>
    <div class="content">
      <div ref="echartRef" style="height: 300px;"></div>
    </div>
  </div>
</template>

<style scoped></style>
